package com.example.learn_mybatis.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.learn_mybatis.pojo.*;
import com.example.learn_mybatis.service.IRolePermissionsService;
import com.example.learn_mybatis.service.IRolesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chen
 * @since 2025-07-11
 */
@RestController
@RequestMapping("/roles")
public class RolesController {
    @Autowired
    private IRolesService rolesService;

    @Autowired
    private IRolePermissionsService rolePermissionsService;

    /**
     * 获取角色列表
     * @param pageParam
     * @return
     */
    @GetMapping
    public Result getRoles(PageParam pageParam) {
        Pager allRoles = rolesService.getAllRoles(pageParam.getSize(), pageParam.getPage());
        return Result.success(allRoles);
    }

    /**
     * 新增角色
     * @param roles
     * @return
     */
    @PostMapping
    public Result addRoles(@RequestBody Roles roles) {
        rolesService.save(roles);
        return Result.success();
    }

    /**
     * 修改角色
     * @param roles
     * @return
     */
    @PutMapping
    public Result updateRoles(@RequestBody Roles roles) {
        boolean b = rolesService.updateById(roles);
        if(b){
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @DeleteMapping
    public Result deleteRoles(Integer id) {
        boolean b = rolesService.removeById(id);
        if(b){
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 获取角色的所有权限
     * @param pageParam
     * @return
     */
    @GetMapping("/permissions")
    public Result getRolePermissin(PageParam pageParam) {

        Pager rolePermissions = rolePermissionsService.getRolePermissionById(pageParam.getId(), pageParam.getSize(), pageParam.getPage());

        return Result.success(rolePermissions);
    }


    /**
     * 新增角色权限
     * @param permissionParam
     * @return
     */
    @PostMapping("/permissions")
    public Result addRolePermissin(@RequestBody PermissionParam permissionParam) {

        boolean b = rolePermissionsService.batchSavePermissions(permissionParam);

        if(b){
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 批量删除角色权限
     * @param permissionParam
     * @return
     */
    @DeleteMapping("/permissions")
    public Result deleteRolePermissin(@RequestBody PermissionParam permissionParam) {
        rolePermissionsService.batchRemovePermission(permissionParam);
        return Result.success();
    }

}
